<template>
  <div style="height: 100%;">
    <crud-table ref="crudTableRef" :config="positionConfig">
      <!-- 添加导入按钮到表格头部 -->
      <template #table-header-left>
        <n-button 
          @click="handleImport"
          class="custom-button"
          quaternary
        >
          <template #icon>
            <n-icon>
              <import-outlined />
            </n-icon>
          </template>
          导入
        </n-button>
        <n-button 
          @click="handleSort"
          class="custom-button"
          quaternary
        >
          <template #icon>
            <n-icon>
              <drag-outlined />
            </n-icon>
          </template>
          排序
        </n-button>
      </template>

      <!-- 添加子岗位按钮 -->
      <template #table-actions="{ row }">
        <n-button
          size="small"
          quaternary
          type="primary"
          @click="handleAddChild(row)"
        >
          添加子岗位
        </n-button>
      </template>
    </crud-table>

    <!-- 导入弹窗 -->
    <n-modal
      v-model:show="showImportModal"
      :mask-closable="false"
      preset="card"
      title="导入岗位"
      style="width: 600px"
      size="small"
    >
      <n-spin :show="uploadLoading">
        <n-form
          ref="importFormRef"
          :model="importForm"
          :rules="importRules"
          label-placement="left"
          label-width="100"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="Excel文件" path="file">
            <n-upload
              accept=".xlsx,.xls"
              :default-upload="false"
              :max="1"
              :disabled="uploadLoading || importLoading"
              @change="handleUploadChange"
            >
              <n-button :disabled="uploadLoading || importLoading">
                选择文件
              </n-button>
            </n-upload>
          </n-form-item>
          <n-form-item label="下载模板">
            <n-space vertical>
              <n-button
                type="primary"
                @click="downloadTemplate"
                :disabled="uploadLoading || importLoading"
              >
                下载导入模板
              </n-button>
              <span>请按模板格式填写，岗位名称和编码为必填项</span>
            </n-space>
          </n-form-item>
        </n-form>
      </n-spin>
      <template #footer>
        <n-space justify="end">
          <n-button
            @click="showImportModal = false"
            :disabled="uploadLoading || importLoading"
          >
            取消
          </n-button>
          <n-button
            type="primary"
            :loading="importLoading"
            :disabled="!importForm.file || uploadLoading"
            @click="handleImportSubmit"
          >
            确定导入
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 排序弹窗 -->
    <n-modal
      v-model:show="showSortModal"
      :mask-closable="false"
      preset="card"
      title="岗位排序"
      style="width: 600px"
      size="small"
    >
      <n-scrollbar style="max-height: 500px">
        <draggable
          v-model="sortableData"
          item-key="id"
          :animation="150"
          class="sort-list"
        >
          <template #item="{ element }">
            <div class="sort-item">
              <n-icon size="20" class="drag-handle">
                <drag-outlined />
              </n-icon>
              <span>{{ element.name }}</span>
            </div>
          </template>
        </draggable>
      </n-scrollbar>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showSortModal = false">取消</n-button>
          <n-button
            type="primary"
            :loading="sortLoading"
            @click="handleSortSubmit"
          >
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { h, ref, onMounted, watch, computed } from 'vue'
import { NButton, NTag, useMessage, NModal, NForm, NFormItem, NUpload, NIcon, NSpin, NSpace, NScrollbar } from 'naive-ui'
import { ImportOutlined, DragOutlined, PlusOutlined } from '@vicons/antd'
import draggable from 'vuedraggable'
import moment from 'moment'
import CrudTable from '@/components/CrudTable/index.vue'
import request from '@/utils/request'
import ImageUpload from '@/components/ImageUpload/index.vue'

const message = useMessage()
const crudTableRef = ref(null)
 
// 添加计算属性获取树形数据
const treeData = computed(() => {
  const data = crudTableRef.value?.tableData || []
  console.log('岗位数据:', buildTreeOptions(data))
  return buildTreeOptions(data)
})

// 修改构建树形选项方法
const buildTreeOptions = (data) => {
  if (!Array.isArray(data)) return []
  
  // 构建id到节点的映射
  const idMap = new Map()
  data.forEach(item => {
    idMap.set(item.id, { ...item })
  })
  
  // 构建树形结构
  const result = []
  data.forEach(item => {
    const node = idMap.get(item.id)
    if (!item.parent_id) {
      result.push(node)
    } else if (idMap.has(item.parent_id)) {
      const parent = idMap.get(item.parent_id)
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(node)
    } else {
      result.push(node)
    }
  })

  // 递归删除空的children属性
  const removeEmptyChildren = (nodes) => {
    nodes.forEach(node => {
      if (node.children && node.children.length === 0) {
        delete node.children
      } else if (node.children) {
        removeEmptyChildren(node.children)
      }
    })
  }

  removeEmptyChildren(result)
  return result
}
 
// 在组件挂载时加载选项
onMounted(() => { 
})

// 导入相关
const showImportModal = ref(false)
const importLoading = ref(false)
const uploadLoading = ref(false)
const importFormRef = ref(null)
const importForm = ref({ file: null })

// 排序相关
const showSortModal = ref(false)
const sortLoading = ref(false)
const sortableData = ref([])

// 修改处理添加子岗位方法
const handleAddChild = (row) => {
  crudTableRef.value?.handleAdd({
    parent_id: row.id
  })
}

// 下载模板
const downloadTemplate = async () => {
  try {
    const templateData = [
      ['岗位名称', '岗位编码', '上级岗位编码', '图标', '排序', '描述'],
      ['总经理', 'GM', '', '', 1, '公司最高负责人'],
      ['技术总监', 'CTO', 'GM', '', 2, '技术部门负责人']
    ]
    
    const XLSX = await import('xlsx')
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.aoa_to_sheet(templateData)
    
    ws['!cols'] = [
      { wch: 20 }, // 岗位名称列宽
      { wch: 20 }, // 岗位编码列宽
      { wch: 20 }, // 上级岗位编码列宽
      { wch: 30 }, // 图标列宽
      { wch: 10 }, // 排序列宽
      { wch: 30 }  // 描述列宽
    ]
    
    XLSX.utils.book_append_sheet(wb, ws, '岗位导入模板')
    XLSX.writeFile(wb, '岗位导入模板.xlsx')
  } catch (error) {
    message.error('模板下载失败')
  }
}

// 处理排序
const handleSort = () => {
  sortableData.value = [...crudTableRef.value?.tableData || []]
  showSortModal.value = true
}

// 处理排序提交
const handleSortSubmit = async () => {
  try {
    sortLoading.value = true
    const sortData = sortableData.value.map((item, index) => ({
      id: item.id,
      sort: index + 1
    }))

    await request.put('/positions/batch-sort', { items: sortData })
    message.success('排序更新成功')
    showSortModal.value = false
    crudTableRef.value?.fetchData()
  } catch (error) {
    message.error('排序更新失败')
  } finally {
    sortLoading.value = false
  }
}

const positionConfig = ref({
  title: '岗位管理',
  apiPrefix: '/positions',
  primaryKey: 'id',
  childrenKey: 'children',

  // 禁用分页
  pagination: false,
  
  // 启用基础操作
  creatable: true,
  editable: true,
  deletable: true,
  switchable: true,
  switchKey: 'status',

  // 表格配置
  tableConfig: {
    pagination: false,
    bordered: false,
    size: 'medium',
    defaultExpandAll: true,
    scrollX: 1400,
    childrenKey: 'children'
  },

  // 表格列配置
  columns: [
    {
      title: '岗位名称',
      key: 'name', 
      ellipsis: true
    },
    {
      title: '岗位编码',
      key: 'code', 
      ellipsis: true
    },
    {
      title: '图标',
      key: 'icon', 
      render: (row) => {
        if (!row.icon) return null
        return h('img', {
          src: row.icon,
          style: {
            width: '24px',
            height: '24px',
            objectFit: 'cover',
            borderRadius: '4px'
          }
        })
      }
    },
    {
      title: '描述',
      key: 'description', 
      ellipsis: true
    }, 
    {
      title: '创建时间',
      key: 'created_at', 
      ellipsis: true,
      render: (row) => {
        return row.created_at && moment(row.created_at).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      title: '更新时间',
      key: 'updated_at', 
      ellipsis: true,
      render: (row) => {
        return row.updated_at && moment(row.updated_at).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  ],

  // 自定义操作按钮配置
  customActions: [
    {
      label: '添加',
      type: 'primary',
      size: 'small',
      quaternary: true,
      icon: () => h(PlusOutlined),
      onClick: handleAddChild
    }
  ],

  // 表单配置
  formConfig: {
    width: '600px',
    labelWidth: 100,
    labelPlacement: 'left',
    requireMarkPlacement: 'right-hanging'
  },

  // 表单字段配置
  formFields: [
    {
      label: '上级岗位',
      key: 'parent_id',
      type: 'tree-select',
      span: 24,
      options: treeData,
      clearable: true,
      filterable: true,
      placeholder: '请选择上级岗位',
      defaultExpandAll: true,
      labelField: 'name',
      keyField: 'id',
      childrenField: 'children',
      disabled: (formData) => !!formData.parent_id,
      separator: ' / ',
      consistentMenuWidth: true,
      nodeProps: (option) => ({
        prefix: () => option.children ? '📁' : '📄'
      }),
      renderLabel: (option) => {
        return option.name
      },
      renderPrefix: () => '🌲',
      virtualScroll: true,
      maxHeight: 300
    },
    {
      label: '岗位名称',
      key: 'name',
      type: 'input',
      span: 24,
      required: true,
      placeholder: '请输入岗位名称'
    },
    {
      label: '岗位编码',
      key: 'code',
      type: 'input',
      span: 24,
      required: true,
      placeholder: '请输入岗位编码'
    },
    {
      label: '图标',
      key: 'icon',
      type: 'custom',
      span: 24,
      render: ({ value, onChange }) => {
        return h(ImageUpload, {
          value,
          'onUpdate:value': onChange
        })
      }
    },
    {
      label: '描述',
      key: 'description',
      type: 'textarea',
      span: 24,
      placeholder: '请输入描述'
    }
  ],

  // 表单验证规则
  rules: {
    name: { required: true, message: '请输入岗位名称', trigger: 'blur' },
    code: { required: true, message: '请输入岗位编码', trigger: 'blur' }
  }
})

// 导入相关方法
const handleImport = () => {
  showImportModal.value = true
}

// 导入表单验证规则
const importRules = {
  file: {
    required: true,
    message: '请选择Excel文件',
    validator: (rule, value) => {
      if (!value) return new Error('请选择Excel文件')
      if (!value.file) return new Error('文件上传失败')
      
      const fileName = value.file.name.toLowerCase()
      const isExcel = /\.(xlsx|xls)$/.test(fileName)
      if (!isExcel) {
        return new Error('只支持.xlsx、.xls格式的Excel文件')
      }
      
      const maxSize = 10 * 1024 * 1024 // 10MB
      if (value.file.size > maxSize) {
        return new Error('文件大小不能超过10MB')
      }
      
      return true
    },
    trigger: ['change']
  }
}

// 处理文件上传改变
const handleUploadChange = async ({ file }) => {
  try {
    if (!file || !file.file) {
      message.error('文件上传失败')
      return
    }

    const fileName = file.file.name.toLowerCase()
    const isExcel = /\.(xlsx|xls)$/.test(fileName)
    
    if (!isExcel) {
      message.error('只支持.xlsx、.xls格式的Excel文件')
      return
    }
    
    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.file.size > maxSize) {
      message.error('文件大小不能超过10MB')
      return
    }
    
    uploadLoading.value = true
    importForm.value.file = file
  } finally {
    uploadLoading.value = false
  }
}

// 处理导入提交
const handleImportSubmit = async () => {
  try {
    await importFormRef.value?.validate()
    importLoading.value = true
    const formData = new FormData()
    formData.append('file', importForm.value.file.file)

    await request.post('/positions/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    message.success('导入成功')
    showImportModal.value = false
    importForm.value.file = null
    crudTableRef.value?.fetchData()
  } finally {
    importLoading.value = false
  }
}
 
</script>

<style lang="scss" scoped>
.custom-button {
  margin-right: 12px;
}

.sort-list {
  padding: 8px;
}

.sort-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: move;

  .drag-handle {
    margin-right: 8px;
    cursor: move;
  }
}

:deep(.n-tree-select) {
  width: 100%;
}

:deep(.n-button.n-button--quaternary) {
  opacity: 1;
}

:deep(.n-data-table-td:hover .n-button.n-button--quaternary) {
  opacity: 1;
}

// 添加省略号的tooltip样式
:deep(.n-data-table-td) {
  .n-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
  }
}
</style>
